package com.atguigu.eduservice.controller;


import com.atguigu.common.R;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.feign.VodFeign;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.ELeanExeception;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author Panghl
 * @since 2021-01-06
 */
@RestController
@RequestMapping("/eduservice/video")
@Api(value = "小节管理")
public class EduVideoController {

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private VodFeign vodFeign;

    @ApiOperation(value = "根据id获取小节信息")
    @GetMapping("/get/{id}")
    public R get(@PathVariable(value = "id") String id) {
        return R.ok().data("video", eduVideoService.getById(id));
    }

    @ApiOperation(value = "新增小节")
    @PostMapping("/add")
    public R add(@RequestBody EduVideo eduVideo) {
        try {
            if (eduVideo != null) {
                eduVideoService.save(eduVideo);
                return R.ok();
            }
            return R.error().message("小节信息不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation(value = "修改小节")
    @PostMapping("/update")
    public R update(@RequestBody EduVideo eduVideo) {
        try {
            if (eduVideo != null) {
                eduVideoService.updateById(eduVideo);
                return R.ok();
            }
            return R.error().message("小节信息不能为空");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation(value = "删除小节，删除对应阿里云的视频")
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") String id) {
        try {
            EduVideo eduVideo = eduVideoService.getById(id);
            String videoSourceId = eduVideo.getVideoSourceId();
            if (!StringUtils.isBlank(videoSourceId)) {
                R result = vodFeign.removeAlyVideo(videoSourceId);
                System.out.println(result);
                if (result.getCode() == 20001){
                    throw new ELeanExeception(20001,"删除视频失败，熔断器....");
                }
            }
            eduVideoService.removeById(id);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

}
